package com.cliff.joinus.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Stack;

import org.cybergarage.upnp.Device;
import org.cybergarage.upnp.std.av.server.DC;
import org.cybergarage.upnp.std.av.server.UPnP;
import org.cybergarage.upnp.std.av.server.object.DIDLLite;
import org.cybergarage.upnp.std.av.server.object.container.ContainerNode;
import org.cybergarage.xml.Node;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockListActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;
import com.androidquery.AQuery;
import com.cliff.joinus.Constants;
import com.cliff.joinus.JoinusControlPoint;
import com.cliff.joinus.LocalMediaDataManager;
import com.cliff.joinus.RendererMediator;
import com.cliff.joinus.Constants.ITEMNODE_TYPE;
import com.cliff.joinus.LocalMediaDataManager.FILE_TYPE;
import com.cliff.joinus.LocalMediaDataManager.MEDIA_TYPE;
import com.cliff.joinus.RendererMediator.MEDIATOR_OPERATION;
import com.cliff.joinus.R;

public class BrowseMediaServerActivity extends SherlockListActivity {

	protected final int[][] ACTIONBARMENU = new int[][]{Constants.AB_BACK, Constants.AB_REFRESH, Constants.AB_SELECT_RENDERER};
	protected ArrayAdapter<Node> mAdapter = null;
	protected Device mMediaServer = null;
	protected String ROOT_OBJECT_ID = "0";
	protected Stack<String> stack = new Stack<String>();
	protected Node mNode = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        Intent intent = getIntent();
		String udn = intent.getStringExtra(JoinusControlPoint.EXTRA_UDN);
		mMediaServer = JoinusControlPoint.getInstance().getDevice(udn);
		stack.push(ROOT_OBJECT_ID);
		
		ArrayList<Node> list = new ArrayList<Node>();
		mAdapter = new ArrayAdapter<Node>(this,
				R.layout.item_line_name_desc, list) {
			@Override
			public View getView(int position, View convertView, ViewGroup parent) {

				if (convertView == null) {
					LayoutInflater inflater = (LayoutInflater) getApplicationContext()
							.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
					convertView = inflater.inflate(
							R.layout.item_line_name_desc, null);
				} 
				Node data = getItem(position);
//				AQuery listItemAq = new AQuery(convertView);
				
				AQuery aq = new AQuery(convertView);
				aq.id(R.id.lineicon).image(getIconResId(data.getNodeValue(UPnP.CLASS)));
				aq.id(R.id.linename).text(data.getNodeValue(DC.TITLE));
				aq.id(R.id.linedesc).text("");
				return convertView;
			}
		};

		setListAdapter(mAdapter);
		setTitle(mMediaServer.getFriendlyName());
	}
	
	protected boolean isFolder(String upnpClass) {
		if (null == upnpClass)
			return false;		
		if (upnpClass.startsWith("object.container"))
			return true;
		
		return false;		
	}
	
	protected int getIconResId(String upnpClass) {
		if (null != upnpClass) {
			if (upnpClass.startsWith(JoinusControlPoint.OBJECT_CONTAINER))
				return R.drawable.file_folder;
			if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_IMAGE))
				return R.drawable.file_photo;
			if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_AUDIO))
				return R.drawable.file_music;
			if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_VIDEO))
				return R.drawable.file_video;
		}
		return R.drawable.file_unknown;		
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		update();
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			
		MainActivity.initMenu(menu, ACTIONBARMENU);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (android.R.id.home == item.getItemId()) {
			finish();
			return true;
		}
		
		if (Constants.GROUP_COMMON == item.getGroupId()) {
			switch(item.getItemId()) {
			case Constants.ITEM_BACK:
				onBackPressed();
				break;
			case Constants.ITEM_REFRESH:
				break;
			}
		}

		return true;
	}
	
	

	@Override
	public void onBackPressed() {

		if (stack.empty())
			finish();

		stack.pop();
		if (stack.empty())
			finish();
		else
			update();
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		// TODO Auto-generated method stub
		Node node = mAdapter.getItem(position);
		String upnpClass = node.getNodeValue(UPnP.CLASS); 
		if (isFolder(upnpClass)) {
			stack.push(node.getAttributeValue(DIDLLite.ID));
			update();
		}
		else {
			//item
			if (null == JoinusControlPoint.getInstance().getSelectedRendererUdn()) {
				//local play
				playUrl(node.getNodeValue(DIDLLite.RES), upnpClass);
			}
			else {
				//remote play

				//should set current list to mediator
				//should call PlayControlActivity here
				
				RendererMediator mediator = JoinusControlPoint.getInstance().getSelectedRendererMediator();
				if (null == mediator) {
					Toast.makeText(this, "Mediator is null, renderer not ready", Toast.LENGTH_SHORT).show();
					return;
				}
				
				ArrayList<Node> nodeList = new ArrayList<Node>();
				if (null != mNode) {
					for (int i = 0; i < mNode.getNNodes(); i++) {
						nodeList.add(mNode.getNode(i));
					}
				}
				
				mediator.init(ITEMNODE_TYPE.EXTERNAL_ITEMNODE, position, nodeList);
				mediator.operate(MEDIATOR_OPERATION.PLAYPAUSE, position);
				
				Intent intent = new Intent(this, PlayControlActivity.class);
				startActivity(intent);
			}
		}
//		super.onListItemClick(l, v, position, id);
	}
	
	protected String getNodeDisplayName(Node node) {
		return node.getNodeValue("dc:title");
	}
	
	protected void update() {
		BrowseTask task = new BrowseTask();
		task.execute(stack.peek());
	}
	
	protected void updateListView(Node node) {
		int count = 0;
		mNode = node;
		if (null != node)
			count = node.getNNodes();
		mAdapter.clear();
		for (int i = 0; i < count; i++) {
			mAdapter.add(node.getNode(i));
		}
		mAdapter.notifyDataSetChanged();
	}
	
	protected void playUrl(String url, String upnpClass) {
		if (null == upnpClass)
			return;

		if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_IMAGE))
			LocalMediaDataManager.getInstance().playExternal(url, MEDIA_TYPE.IMAGE, FILE_TYPE.EXTERNAL_URL);
		else if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_AUDIO))
			LocalMediaDataManager.getInstance().playExternal(url, MEDIA_TYPE.AUDIO, FILE_TYPE.EXTERNAL_URL);
		else if (upnpClass.startsWith(JoinusControlPoint.OBJECT_ITEM_VIDEO))
			LocalMediaDataManager.getInstance().playExternal(url, MEDIA_TYPE.VIDEO, FILE_TYPE.EXTERNAL_URL);
	}

	protected class BrowseTask extends AsyncTask<String, Void, Node> {

		@Override
		protected void onPostExecute(Node result) {
			// TODO Auto-generated method stub
			setSupportProgressBarIndeterminateVisibility(false);
			updateListView(result);
			getListView().setClickable(true);
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			setSupportProgressBarIndeterminateVisibility(true);
			getListView().setClickable(false);
			super.onPreExecute();
		}

		@Override
		protected Node doInBackground(String... params) {
			// TODO Auto-generated method stub
			Node node = JoinusControlPoint.getInstance().browseDirectChildren(mMediaServer, params[0]);
			return node;
		}

	}

}
